package com.structure.project.common.annotation.verify;

import javax.validation.ConstraintValidator;
import javax.validation.ConstraintValidatorContext;

/**
 * 枚举校验器
 *
 * @author liuz
 * @date 2021/01/04 18:41
 **/
public class EnumValueValidator implements ConstraintValidator<EnumValue, Object> {

    private String[] strValues;

    private int[] intValues;

    private boolean canNull;

    @Override
    public void initialize(EnumValue constraintAnnotation) {
        strValues = constraintAnnotation.strValues();
        intValues = constraintAnnotation.intValues();
        canNull = constraintAnnotation.canNull();
    }

    @Override
    public boolean isValid(Object value, ConstraintValidatorContext context) {

        if (value == null && canNull) {
            return true;
        }
        if (value instanceof String) {
            for (String s : strValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        } else if (value instanceof Integer) {
            for (Integer s : intValues) {
                if (s.equals(value)) {
                    return true;
                }
            }
        }
        return false;

    }

}
